package logger

import (
	"bytes"
	"encoding/json"
	"strings"
	"text/template"
	"time"
)

// Message log message struct
type Message struct {
	FormatType    string
	ContentFormat string
	TimeFormat    string
}

// GetMessage, return formatted message string for output.
func (formatter *Message) GetMessage(logger *Logger) string {
	// init format string
	if formatter.TimeFormat == "" {
		formatter.TimeFormat = time.RFC3339
	}
	if formatter.ContentFormat == "" {
		formatter.ContentFormat = `{{.Color}}{{.LevelString}} [{{.Time}}] {{.Message}} {{.Path}}({{.Line}}) {{.ColorClear}}`
	}

	logBuffer := new(bytes.Buffer)

	if formatter.FormatType == JsonType {
		jsonByte, _ := json.Marshal(logger.Record)
		logBuffer.Write(jsonByte)
	} else {
		logger.Record.Time = time.Now().Format(formatter.TimeFormat)
		tpl := template.Must(template.New("messageFormat").Parse(formatter.ContentFormat))
		tpl.Execute(logBuffer, *logger.Record)
	}

	message := logBuffer.String()
	if strings.Index(message, "\n") != len(message)-1 {
		message += "\n"
	}
	return message
}
